package cn.miju.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.miju.common.exception.ValidateException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Objects;
import java.util.Set;

/**
 * <pre>
 * 参数校验工具类
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-09 22:25
 */
public class ValidationUtil {
    private static final Validator VALIDATOR = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 校验实体类
     */
    public static <T> void validate(T obj) {
        if (Objects.nonNull(obj)) {
            Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(obj);
            if (CollUtil.isNotEmpty(constraintViolations)) {
                StringBuilder validateError = new StringBuilder();
                for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                    validateError.append(constraintViolation.getMessage()).append(";");
                }
                throw new ValidateException(validateError.toString());
            }
        }
    }
    /**
     * 校验实体类返回布尔值
     */
    public static <T> boolean toValidate(T obj) {
        if (Objects.nonNull(obj)) {
            Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(obj);
            return !CollUtil.isNotEmpty(constraintViolations);
        }
        return false;
    }

    /**
     * 通过组来校验实体类
     */
    public static <T> void validate(T obj, Class<?>... group) {
        if (Objects.nonNull(obj)) {
            Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(obj, group);
            if (CollUtil.isNotEmpty(constraintViolations)) {
                StringBuilder validateError = new StringBuilder();
                for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                    validateError.append(constraintViolation.getMessage()).append(";");
                }
                throw new ValidateException(validateError.toString());
            }
        }
    }
}
